<template>
    <div style="width: 1000px;margin: auto">
    <el-card>
        <h1 style="color: #475669">{{video.id==null?'发布':'修改'}}视频页面</h1>
        <el-form label-width="80px">
            <el-form-item label="视频标题">
                <el-input placeholder="请输入标题" v-model="video.title"></el-input>
            </el-form-item>
            <el-form-item label="分区" >
                <el-cascader :options="categoryArr" :show-all-levels="false" @change="handleChange"/>
            </el-form-item>
<!--*****************************************************-->
            <el-form-item>
                <div class="tag-input">
                    <a-select mode="tags" style="width: 766px; margin-top: 17px;" placeholder="请输入标签(限制长度为1-12)"
                              @change="handleChangeTag" size="large" :max-tag-count="5" v-model="selectTags"
                              :dropdown-style="{ maxHeight: '170px', overflowY: 'auto' }" >
                        <a-select-option v-for="item in TagList" :key="item.id"
                                         v-infinite-scroll="load">
                            {{ item.tagName }}
                        </a-select-option>
                    </a-select>
                </div>
            </el-form-item>
<!-- ************************************************************-->
            <el-form-item label="封面">
                <!--   上传组件开始   -->
                <el-upload
                        v-model:file-list="fileList"
                        drag
                        action='http://124.71.182.39:28000/upload/uploadImage'
                        name="file"
                        list-type="picture-card"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove"
                        :on-success="handleSuccess"
                        :headers="headers"
                        :limit="1"
                >
                    <el-icon><Plus /></el-icon>
                </el-upload>

                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
                <!--   上传组件结束   -->
            </el-form-item>

            <el-form-item label="视频简介">
                <div ref="editorContent" style="text-align: left">

                </div>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="postContent">
                    {{video.id==null?'发布':'修改'}}内容</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    </div>
</template>

<script setup>
import {onBeforeUnmount, onMounted, ref, nextTick} from "vue";
//导入文本编辑器
import Editor from "wangeditor";
import TokenAxios from "@/http/request/TokenAxios";
import {ElMessage} from "element-plus";
import SimpleAxios from "@/http/request/SimpleAxios";
import router from "@/router";
import {onBeforeRouteLeave, onBeforeRouteUpdate} from "vue-router";
import axios from "axios";
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
//得到页面中用来装编辑器的div
const editorContent = ref(null);

const categoryArr=ref([]);

const video = ref({title:""})



const TagList = ref([])
const page = ref(0)



const handleChangeTag = (value) => {
    console.log(value)
    // 从 TagList 中匹配用户输入的标签，获取对应的标签ID组成数组
    video.value.tagList = TagList.value
        .filter(tag => value.includes(tag.id))
        .map(tag => tag.id);
    console.log(video.value.tagList)

};


const load = () => {

    if (TagList.value.length > 0 && TagList.value.length % 12 !== 0) {
        // 如果视频数组长度不是4的倍数，说明数据库中没有更多数据了，停止发送请求
        return;
    }

    page.value++;
    TokenAxios.get('http://124.71.182.39:27100/admin/tag?page='+page.value)
        .then((response)=>{
            if (response.state===20000){
                if (response.data.list.length === 0) {
                    // 数据库中没有更多数据了，停止发送请求
                    return;
                }
                // videoArr.value += response.data.data;
                TagList.value = TagList.value.concat(response.data.list);
            }else {
                ElMessage.error(response.message)
            }
        })
}


const loadCategories = ()=>{
    TokenAxios.get('http://124.71.182.39:26000/categories/tree')
        .then((response)=>{
            if (response.state===20000){
                categoryArr.value=response.data;
            }
        })
}

const loginInfo = ref(getUser());
const headers = {
    'Authorization': loginInfo.value.token
};
const handleChange = (value)=> {
    // value就是选中的值
    // 您可以在这里将value赋值给video的上传参数
    // console.log(typeof value)
    video.value.categoryId=parseInt(value[value.length - 1]);
    video.value.videoUrl = localStorage.getItem('returnUrl');
}

let editor = null;
onMounted(()=>{
    loadCategories();
    // getAllTag();
    load();
    editor = new Editor(editorContent.value);
    editor.config.placeholder='请输入内容详情...';
    editor.create();
})

// Function to handle the confirmation
const confirmLeave = (next) => {
    const message = 'Are you sure you want to leave?';
    if (!window.confirm(message)) {
        next(false); // Prevents leaving the route
    } else {
        next(); // Allows leaving the route
    }
};

// Register the beforeRouteLeave hook
onBeforeRouteLeave((to, from, next) => {
    confirmLeave(next);
});

// Handle window closing event
window.onbeforeunload = (event) => {
    const message = 'Are you sure you want to leave?';
    event.returnValue = message; // For most browsers
    return message; // For modern browsers
};

// Register the onBeforeUnmount hook
onBeforeUnmount(() => {
    // Clean up or perform actions before the component is unmounted
    // You can add additional logic here
});

// //和页面元素绑定的内容对象
const handleRemove = (uploadFile, uploadFiles) => {
    // video.value.coverUrl = null;
    //TODO 删除库中的数据
    let url = uploadFile.response.data;
    // axios.post('http://localhost:8080/v1/remove?url='+url)
    //     .then((response)=>{
    //         if (response.data.code===1){
    //             console.log("服务器图片删除完成！")
    //         }
    //     })
}

const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
}

const handleSuccess = (response, uploadFile, uploadFiles) => {
    video.value.coverUrl = response.data;
    ElMessage.success("成功上传封面")
}

const postContent = ()=>{
    if (video.value.coverUrl==null){alert("请选择封面!");return;}
    if (video.value.videoUrl==null){alert("请选择封面!");return;}
    if (video.value.title.trim()==''){alert('标题不能为空!');return;}
        //把富文本编辑器里面的内容取出
        video.value.detail = editor.txt.html();
        video.value.brief=editor.txt.text().slice(0,30);
    //发请求
    TokenAxios.post('http://124.71.182.39:26000/video/addNew',video.value)
        .then((response)=>{
            if (response.state===20000){
                //跳转到成功发布页面

               router.push('/')
            }else {
                ElMessage.error(response.message)
            }
        })
}
</script>

<style scoped>

</style>